﻿using System;
using System.Windows;
using SqueezeboxLib;

namespace SqueezeBoxClient
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow
    {
        private readonly SqueezeboxServer squeezeBoxServer;

        //private SqueezeboxConnection connection;

        public MainWindow()
        {
            InitializeComponent();

            Closing += ApplicationClosing;

            squeezeBoxServer = new SqueezeboxServer("localhost", 9090);
            squeezeBoxServer.ConnectionEstablished += SqueezeboxServerConnectionEstablished;
            squeezeBoxServer.ClientStatusChanged += SqueezeBoxServerClientStatusChanged;
            squeezeBoxServer.MessageReceived += SqueezeboxMessageReceived;
            squeezeBoxServer.PlayersUpdated += SqueezeboxPlayersUpdated;

            listBoxPlayers.ItemsSource = squeezeBoxServer.Players.Values;

            try
            {
                squeezeBoxServer.Connect();
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message, "Connection Failed", MessageBoxButton.OK, MessageBoxImage.Information);
            }

        }

        private void SqueezeBoxServerClientStatusChanged(object sender, ClientStatusChangedEventArgs e)
        {
            Dispatcher.Invoke((Action) (() => listBoxPlayers.Items.Refresh()));
        }

        void SqueezeboxServerConnectionEstablished(object sender, EventArgs e)
        {
            squeezeBoxServer.UpdatePlayers(0, 10);
        }

        void SqueezeboxPlayersUpdated(object sender, EventArgs e)
        {
            Dispatcher.Invoke((Action)(() => listBoxPlayers.Items.Refresh()));
        }

        void SqueezeboxMessageReceived(object sender, MessageReceivedEventArgs args)
        {
            System.Diagnostics.Debug.Print("MSG: " + args.Message);

            Dispatcher.Invoke((Action)(() =>
                {
                    textBlockRespnse.Text = args.Message;
                }));
        }

        private void buttonSend_Click(object sender, RoutedEventArgs e)
        {
            squeezeBoxServer.Send(textBox1.Text);
            textBox1.Text = "";
        }

        void ApplicationClosing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            squeezeBoxServer.Disconnect();
        }

        private void button4_Click(object sender, RoutedEventArgs e)
        {
            squeezeBoxServer.Listen("1");
        }

        private void buttonLaunch_Click(object sender, RoutedEventArgs e)
        {
            if (listBoxPlayers.SelectedItem != null)
            {
                PlayerWindow playerWindow = new PlayerWindow(listBoxPlayers.SelectedItem as SqueezeboxPlayer);
                playerWindow.Show();
            }
        }

    }
}
